package com.dodo.blog.server.impl;

import com.comvai.services.persistence.LowLevel;
import com.comvai.services.persistence.PersistenceManager;
import com.comvai.services.persistence.criteria.Criteria;
import com.comvai.services.persistence.criteria.Restrictions;
import com.dodo.blog.exception.EmailAlreadyExists;
import com.dodo.blog.exception.LoginAlreadyExists;
import com.dodo.blog.model.Account;
import com.dodo.blog.server.AccountService;
import org.apache.commons.codec.digest.DigestUtils;

import javax.inject.Inject;
import java.util.List;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class AccountServiceBean
        extends AbstractServiceBean
        implements AccountService
{
    @Inject
    public AccountServiceBean( @LowLevel PersistenceManager datastore )
    {
        super( datastore );
    }

    @Override
    public void saveAccount( Account account )
    {
        save( account );
    }

    @Override
    public void register( Account account ) throws EmailAlreadyExists, LoginAlreadyExists
    {
        // check if user with email or login exist, if yes throw particular exception
        switch ( account.getLoginType() )
        {
            case OPEN_ID:
            case OAUTH:
            {
                String email = account.getEmail();
                Criteria<Account> criteria = Criteria.create( Account.class );
                criteria.addCriteria( Restrictions.eq( "email", email ) );

                List<Account> list = datastore.list( criteria );
                if ( list.size() > 0 )
                {
                    throw new EmailAlreadyExists();
                }

                break;
            }
            case LOGIN:
            {
                String login = account.getLogin();
                Criteria<Account> criteria = Criteria.create( Account.class );
                criteria.addCriteria( Restrictions.eq( "login", login ) );

                List<Account> list = datastore.list( criteria );
                if ( list.size() > 0 )
                {
                    throw new LoginAlreadyExists();
                }

                // hash account password
                account.setPassword( DigestUtils.md5Hex( account.getPassword() ) );

                break;
            }
        }

        // save account
        saveAccount( account );
    }
}